#!/usr/bin/env python2.6
# -*- encoding:utf-8 -*-


# ---------------------------------------------------------
# Copyright (c) 2011 by João dos Santos Gonçalves,
# Andrea Oliveira da Silva e Glevson da Silva Pinto,
# Foo Figther Game(c) e Foo Fighter(c) 2011.
# ---------------------------------------------------------

#* Project: Foo Fighter Game
#* Release: 09/06/2011
#* Version: 0.11
#* More information: http://code.google.com/p/foo-fighter-game/w/list

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#* Universidade Federal de Alagoas - UFAL/ARAPIRACA
#* Ciência da Computação
#* Disciplina: Laboratório de Programação 1
#* Orientador: Mário Hozano

# ************************************************************************

# This is Foo Fighter Game, an implementation in Python,
# is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
# Foo Fighter is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the
# GNU General Public License along with Plague;
# if not, write to the Free Software Foundation, Inc.

# *************************************************************************



import pygame
from pygame.locals import *

import os, sys, getopt


image_diretorio = os.path.join( "..", "imagens" ) # Recebe a imagem do fundo

class Fundo:
    """
    Fundo do Game
    """
    image = None
    posicao = None
    
    def __init__(self, image="foo_fundo.png"):
    
        if isinstance(image, str):
            image = os.path.join(image_diretorio, image)
            image = pygame.image.load(image).convert()
            # Converte a imagem para e melhora o processamento do da\ imagens.
        
        self.asize = image.get_size()
        self.posicao = [0, -1 * self.asize[1]]
        tela = pygame.display.get_surface() 
        tela_size = tela.get_size()
        
        from math import ceil
        
        largura = (ceil(float(tela_size[0]) / self.asize[0]) + 1) * self.asize[0]
        altura = (ceil(float(tela_size[1]) / self.asize[1]) + 1) * self.asize[1]
        
        back =  pygame.Surface((largura, altura))
        
        for i in range((back.get_size()[0] / self.asize[0])):
            for j in range((back.get_size()[1] / self.asize[1])):
                back.blit(image, (i * self.asize[0], j * self.asize[1]))
        
        self.image = back
            
    
    def draw(self, tela):
        ''' Desenha a tela '''
        tela.blit(self.image, self.posicao)

    def update(self, dt):
        self.posicao[1] = self.posicao[1] + 1
        if (self.posicao[1] > 0):
            self.posicao[1] = self.posicao[1] - self.asize[1]
            
# Fundo

class Game:
    tela = None
    tela_size = None
    run = True
    fundo  = None    
    
    def __init__(self, asize, fullscreen):
        """
        Aqui iniciamos o pygame, a resolução da tela, caption, e por enquanto desativa o mouse
        """
        atores = {}
        pygame.init() 
        flags = DOUBLEBUF
        if fullscreen:
            flags |= FULLSCREEN
        self.tela = pygame.display.set_mode( asize, flags)
        self.tela_size = self.tela.get_size()

        pygame.mouse.set_visible(0) # Deixa o mouse invisivel
        
        pygame.display.set_caption("Foo Fighter v0.11") # Titulo

    def controle_eventos(self):
        """
        Trata os eventos e toma as ações
        """
        for event in pygame.event.get():
            evento = event.type
            if evento in (KEYDOWN, KEYUP):
                k = event.key
        
            if evento == QUIT:
                self.run = False

            elif evento == KEYDOWN:
                if k == K_ESCAPE:
                    self.run = False



   
    def loop_principal(self):
        """
        Laço principal
        """
        # Criamos o fundo
        self.fundo = Fundo('foo_fundo.png')

        # Relogio e o dt que vai limitar o valor de FPS
        clock = pygame.time.Clock()
        dtime = 16

        # Inicia loop principal
        while self.run:
            clock.tick(1000 / dtime)

            # Handle Input Events
            self.controle_eventos()

            self.atores_update( dtime )

            self.atores_draw()
            
            pygame.display.flip()


    def atores_update(self, dtime):
        self.fundo.update( dtime )

    def atores_draw(self):
        self.fundo.draw(self.tela)


# Game
def parse_opts(argv):
    """
    Retorna as informações da linha de comando
    """
    # Analise a linha de commando usando 'getopt'
    try:
        opts, args = getopt.gnu_getopt( argv[ 1 : ],
                                        "hfr:",
                                        [ "help",
                                          "fullscreen",
                                          "resolution=" ] )
    except getopt.GetoptError:
        # Informaçao
        usage()
        sys.exit(2)

    options = {
        "fullscreen":  False,
        "resolution": (640, 480),
        }

    for b, m in opts:
        if b in ( "-f", "--fullscreen" ):
            options[ "fullscreen" ] = True
        elif b in ( "-h", "--help" ):
            usage()
            sys.exit( 0 )
        elif b in ( "-r", "--resolution" ):
            m = m.lower()
            r = m.split( "x" )
            if len( r ) == 2:
                options[ "resolution" ] = r
                continue

            r = m.split( "," )
            if len( r ) == 2:
                options[ "resolution" ] = r
                continue

            r = m.split( ":" )
            if len( r ) == 2:
                options[ "resolution" ] = r
                continue
    # for b, m in opts
    
    r = options[ "resolution" ]
    options[ "resolution" ] = [ int( r[0] ), int( r[1] ) ]
    return options
# parse_opts()

def main(argv):
    ''' Primeiro vamos verificar que estamos no diretorio certo para conseguir encontrar as imagens e outros recursos, e inicializar o pygame com as opcoes passadas pela linha de comando
    '''
    fullpath = os.path.abspath( argv[ 0 ] )
    dir = os.path.dirname( fullpath )
    os.chdir( dir )

    options = parse_opts(argv)
    game = Game( options[ "resolution" ], options[ "fullscreen" ] )


    game.loop_principal()
    
# main()
        
# Aqui executamos tudo
if __name__ == '__main__':
    main(sys.argv)
